package com.myapp.api.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myapp.api.entity.Teacher;
import com.myapp.api.service.TeacherService;
import com.myapp.api.tools.JsonResult;
import com.myapp.api.tools.MD5Utils;
import com.myapp.api.tools.ResultStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

@Api(value = "TeacherController",description = "teacher 表的相关 CURD 操作")
@RestController
@RequestMapping(value = "/teacher", produces = "application/json;charset=UTF-8")
public class TeacherController {
    @Autowired
    private TeacherService service;

    @ApiOperation(value="获取教师信息列表",notes="获取所有的教师信息",produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页多少条", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/all")
    public ResponseEntity<?> getTeachers(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        String orderBy = "CreateTime DESC";
        PageHelper.startPage(pageNum, pageSize, orderBy);
        List<Teacher> teacher = service.getTeachers();

        HttpStatus status = HttpStatus.OK;
        PageInfo<Teacher> records = new PageInfo<>(teacher);
        return new ResponseEntity<PageInfo<Teacher>>(records, status);
    }

    @ApiOperation(value="获取教师详细信息",notes="根据 url 的教师工号来获取详细信息",produces = "application/json")
    @ApiImplicitParam(name = "tid", value = "教师工号", required = true, dataType = "Integer", paramType = "path")
    @GetMapping("/{tid}")
    public ResponseEntity<?> getTeacherByTid(@PathVariable(value = "tid") String tid) {
        if (!tid.equals(0)) {
            Teacher record = service.getTeacherByTid(tid);

            HttpStatus status = HttpStatus.OK;
            Object obj = new Object();
            if (record == null)
                return new ResponseEntity<Object>(obj, status);
            else
                return new ResponseEntity<Teacher>(record, status);
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "id 不能为 0 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        }
    }

    @ApiOperation(value="根据教师名查询课程信息",notes="通过模糊匹配教师名",produces = "application/json")
//    @ApiImplicitParams({
    @ApiImplicitParam(name = "cname", value = "教师名关键词", required = true, dataType = "String", paramType = "query")
//            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", paramType = "query"),
//            @ApiImplicitParam(name = "pageSize", value = "一页多少条", dataType = "Integer", paramType = "query")
//    })
// @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize
    @GetMapping
    public ResponseEntity<?> getTeacherByTname(@RequestParam(value = "tname") String tname) {
        if (!tname.equals("") && !tname.isEmpty()) {
            List<Teacher> dept = null;
            try {
//                String orderBy = "CreateTime DESC";
//                PageHelper.startPage(pageNum, pageSize, orderBy);
                dept = service.getTeacherByTname(URLDecoder.decode(tname, "utf-8"));
//                record = new PageInfo<>(dept);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpStatus status = HttpStatus.OK;
            return new ResponseEntity<List<Teacher>>(dept, status);
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "教师姓名不能为空 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        }
    }

    @ApiOperation(value="新增教师信息",notes="新增教师信息,不允许提交不存在的教师工号",produces = "application/json")
    @PostMapping
    public ResponseEntity<?> addTeacher(@Valid @RequestBody Teacher record, BindingResult bindingResult) {
        String pwd = MD5Utils.encode(String.valueOf(record.getTid()));
        record.setPwd(pwd);
        record.setCreatetime(new Date());

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            Integer findOne = service.getTeacherByOneTid(record.getTid());

            if (!findOne.equals(0)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "重复的教师编号" + record.getTid() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else {
                int result = service.addTeacher(record);
                if (result > 0) {
                    HttpStatus status = HttpStatus.OK;
                    JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                } else {
                    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                    JsonResult jsonResult = new JsonResult(ResultStatus.ADD_DATA_ERROR, "Add Teacher Data is Error");
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                }
            }
        }
    }

    @ApiOperation(value="删除教师",notes="根据 url 的 id 来删除教师",produces = "application/json")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer", paramType = "path")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delTeacherById(@PathVariable(value = "id") Integer id) {
        if (!id.equals(0)) {
            int result = service.deleteTeacherById(id);
            if (result > 0) {
                HttpStatus status = HttpStatus.OK;
                JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                return new ResponseEntity<JsonResult>(jsonResult, status);
            } else {
                HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                JsonResult jsonResult = new JsonResult(ResultStatus.DELETE_DATA_ERROR, "Delete  Teacher is Error, the id is" + id + " !!!");
                return new ResponseEntity<JsonResult>(jsonResult, status);
            }
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "id 不能为 0 !!!");
            return new ResponseEntity<JsonResult>(result, status);
        }
    }

    @ApiOperation(value="修改教师信息",notes="删除教师信息,不允许提交不存在的教师工号",produces = "application/json")
    @PutMapping
    public ResponseEntity<?> putTeacher(@Valid @RequestBody Teacher record, BindingResult bindingResult) {
        record.setUpdatetime(new Date());

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            Integer findOne = service.getTeacherByOneTid(record.getTid());

            if (!findOne.equals(1)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "重复的教师编号" + record.getTid() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else {
                int result = service.putTeacher(record);
                if (result > 0) {
                    HttpStatus status = HttpStatus.OK;
                    JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                } else {
                    HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                    JsonResult jsonResult = new JsonResult(ResultStatus.UPDATE_DATA_ERROR, "Update Teacher is error");
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                }
            }
        }
    }
}
